<template>
  <div id="subject_manage" class="container">
    <div class="content">
      <!-- <div class="title">科目管理</div> -->
      <div class="panel">
        <div class="condition">
          <div class="row_one">
            <el-input
              style="width: 3.5rem;"
              placeholder="搜索 科目名称"
              v-model="searchText"
              class="input_search"
              clearable
            ></el-input>
            <div
              @click="searchSubject()"
              v-if="hasApi('subjectList')"
              class="search_btn"
              style="margin-left:0.1rem;"
            >搜索</div>
            <div class="right_btn" v-if="hasApi('subjectAdd')" @click="openAdd()">新&nbsp&nbsp增</div>
          </div>
        </div>

        <div>
          <table class="table" cellspacing="0">
            <thead class="thead">
              <tr>
                <td style="width: 2rem;">序号</td>
                <td style="width: 4rem;">科目名称</td>
                <td style="width: 4rem;">子科目名称</td>
                <td style="width: 4rem;">所属机构</td>
                <td style="width: 4rem;">创建人</td>
                <td style="width: 4rem;">创建时间</td>
                <td style="width: 2rem;">操作</td>
              </tr>
            </thead>
            <tbody class="tbody">
              <tr v-for="item,index in subjectList">
                <td>{{item.orderBy}}</td>
                <td>{{item.name}}</td>
                <td>{{item.subTagName}}</td>
                <td>{{item.orgName}}</td>
                <td>{{item.createUserName}}</td>
                <td>{{item.createTime}}</td>
                <td>
                  <span
                    class="operate_btn"
                    @click="handleEdit(index,item)"
                    v-if="hasApi('subjectUpdate')"
                  >编辑</span>
                  &nbsp;
                  <span
                    v-if="hasApi('subjectDelete')"
                    class="operate_btn"
                    @click="handleDelete(index,item)"
                  >删除</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <el-pagination
          class="page"
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="tabledisplayObj.currentPage"
          @size-change="pageSizeChange"
          @current-change="tabledisplayChangePage"
          :total="tabledisplayObj.total"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      title="新建科目"
      :visible.sync="dialogFormVisible"
      center
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form :model="form">
        <el-form-item
          label="科目"
          :label-width="formLabelWidth"
          :rules="[
      { required: true, message: '科目不能为空'}]"
        >
          <el-input
            style="width:70%"
            maxlength="30"
            clearable
            v-model="form.name"
            placeholder="请输入科目"
          ></el-input>
        </el-form-item>
        <el-form-item label="子科目" :label-width="formLabelWidth" :rules="[
       { required: true, message: '子科目不能为空'}]">
          <el-tag
            :key="tag.subSubjectName"
            v-for="tag in form.subSubjectList"
            closable
            :disable-transitions="false"
            @close="handleClose(tag,1)"
          >{{tag.subSubjectName}}</el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm(1)"
            @blur="handleInputConfirm(1)"
          ></el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput(1)">新增子科目</el-button>
        </el-form-item>
        <el-form-item
          label="序号"
          :label-width="formLabelWidth"
          :rules="[
      { required: true, message: '序号不能为空'}]"
        >
          <el-input-number
            class="newclassroomNumber"
            style="width:70%;"
            @change="valueChange"
            v-model="form.orderBy"
            :min="1"
            :max="9999"
            label="请输入排序号"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" :class="{disable:inputVisible}" @click="addCofim()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="编辑科目"
      :visible.sync="dialogFormVisible_update"
      center
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form :model="form_update">
        <el-form-item
          label="科目"
          :label-width="formLabelWidth"
          :rules="[
      { required: true, message: '科目不能为空'}]"
        >
          <el-input
            style="width:70%"
            maxlength="30"
            clearable
            v-model="form_update.name"
            placeholder="请输入科目"
          ></el-input>
        </el-form-item>
        <el-form-item label="子科目" :label-width="formLabelWidth" :rules="[
       { required: true, message: '子科目不能为空'}]">
          <el-tag
            :key="tag.subSubjectName"
            v-for="tag in form_update.subSubjectList"
            :closable="tag.deletableOfSubSubject == true || tag.deletableOfSubSubject == undefined "
            :disable-transitions="false"
            @close="handleClose(tag,2)"
          >{{tag.subSubjectName}}</el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput_update"
            size="small"
            @keyup.enter.native="handleInputConfirm(2)"
            @blur="handleInputConfirm(2)"
          ></el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput(2)">新增子科目</el-button>
        </el-form-item>
        <el-form-item
          label="序号"
          :label-width="formLabelWidth"
          :rules="[
      { required: true, message: '序号不能为空'}]"
        >
          <el-input-number
            class="newclassroomNumber"
            style="width:70%;"
            @change="valueChange"
            v-model="form_update.orderBy"
            :min="1"
            :max="9999"
            label="请输入排序号"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible_update = false">取 消</el-button>
        <el-button type="primary" :disabled="inputVisible" @click="updateCofim()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from "vuex"; //先要引入
import { constants } from "fs";
let vm;
let user;
export default {
  data() {
    return {
      searchText: "", //搜索框输入文本
      tabledisplayObj: {
        currentPage: 1,
        size: 10,
        total: 0
      },

      inputVisible: false,
      inputValue: "",
      isShowSearch: false,
      subjectList: [],
      dialogFormVisible: false,
      dialogFormVisible_update: false,
      formLabelWidth: "140px",
      orgList: [],
      form: {
        name: "",
        orderBy: "",
        orgId: 0,
        subSubjectList: []
      },
      form_update: {
        name: "",
        orderBy: "",
        orgId: "",
        subSubjectList: [],
        subjectId: 0
      },
      /**角色权限限制 */
      disableByRole: {
        newBtn: "visible",
        editorBtn: true,
        deleteBtn: true
      }
    };
  },
  components: {},
  watch: {
    // 如果 `searchText` 发生改变，这个函数就会运行
    searchText: function(newSearchText, oldSearchText) {
      if (newSearchText == "") {
        this.tabledisplayObj.currentPage = 1;
        this.isShowSearch = false;
        this.initData();
      }
    }
  },
  methods: {
    openAdd() {
      vm.form = {
        name: "",
        orderBy: "",
        orgId: 0,
        subSubjectList: []
      };
      vm.inputValue = "";
      vm.inputVisible = false;
      vm.dialogFormVisible = true;
    },
    handleClose(tag, val) {
      if (val == 1) {
        this.form.subSubjectList.splice(
          this.form.subSubjectList.indexOf(tag),
          1
        );
      } else {
        this.form_update.subSubjectList.splice(
          this.form_update.subSubjectList.indexOf(tag),
          1
        );
      }
    },
    showInput(val) {
      vm.inputVisible = true;
      this.$nextTick(_ => {
        if (val == 1) {
          this.$refs.saveTagInput.$refs.input.focus();
        } else {
          this.$refs.saveTagInput_update.$refs.input.focus();
        }
      });
    },
    handleInputConfirm(val) {
      let inputValue = this.inputValue;
      if (!inputValue) {
        this.inputVisible = false;
        return;
      }
      if (tool.judge("name", inputValue)) {
        if (val == 1) {
          this.form.subSubjectList.push({ subSubjectName: inputValue });
        } else {
          this.form_update.subSubjectList.push({ subSubjectName: inputValue });
        }
        this.inputVisible = false;
        this.inputValue = "";
      } else {
        this.$message.warning("请输入有效的子科目名称");
        this.inputValue = "";
        if (val == 1) {
          this.$refs.saveTagInput.$refs.input.focus();
        } else {
          this.$refs.saveTagInput_update.$refs.input.focus();
        }
        return;
      }
    },
    valueChange(val) {
      console.log(val);
      if (!tool.judge("integer0", val)) {
        this.$message.warning("需为正整数");
        val = "";
      }
    },
    /**
    /**
     * 初始化数据
     */
    initData() {
      let paras = {
        currPage: this.tabledisplayObj.currentPage,
        pageSize: this.tabledisplayObj.size
      }; //设置请求列表参数
      if (this.isShowSearch) {
        paras.name = this.searchText;
      }
      this.getData(paras);
      this.disableOperationByRole();
    },
    /**根据角色权限限制操作 */
    disableOperationByRole() {
      switch (user.roleMode) {
        //超级管理员
        case 0: {
          this.disableByRole = {
            newBtn: "hidden",
            editorBtn: false,
            deleteBtn: false
          };
          break;
        }
        //机构管理员
        case 1: {
          this.disableByRole = {
            newBtn: "visible",
            editorBtn: true,
            deleteBtn: true
          };
          break;
        }
        //校区管理员
        case 2: {
          this.disableByRole = {
            newBtn: "hidden",
            editorBtn: false,
            deleteBtn: false
          };
          break;
        }
      }
    },
    /**
     * 抽取出来获取列表
     */
    getData(paras) {
      let subjecttemp = []; //临时存放列表
      api.subjectList(paras).then(function(data) {
        // console.log(data);
        if (data.resultCode == 2000) {
          subjecttemp = data.list;
          for (let i = 0; i < subjecttemp.length; i++) {
            // console.log(subjecttemp[i].subjectId);
            subjecttemp[i].createTime = subjecttemp[i].createTime.split(" ")[0];
            subjecttemp[i].subTagName = "";
            for (let n = 0; n < subjecttemp[i].subSubjectList.length; n++) {
              subjecttemp[i].subTagName +=
                subjecttemp[i].subTagName == ""
                  ? subjecttemp[i].subSubjectList[n].subSubjectName
                  : "," + subjecttemp[i].subSubjectList[n].subSubjectName;
            }
          }
          vm.tabledisplayObj.total = data.totalCount;
          vm.subjectList = subjecttemp;
          // console.log(vm.subjectList);
        } else {
          vm.$message.error(data.message);
        }
      });
    },
    pageSizeChange: function(val) {
      this.tabledisplayObj.size = val;
      this.initData();
    },
    /**表格显示形式翻页 */
    tabledisplayChangePage(val) {
      this.tabledisplayObj.currentPage = val;
      this.initData();
    },
    /**
     * 向列表中添加数据
     */
    addCofim() {
      if (this.form.name == "") {
        this.$message.warning("科目名称不能为空");
        return;
      }
      if (!tool.judge("classname", this.form.name)) {
        this.$message.warning("请输入有效的科目名称");
        return;
      }
      if (this.form.orderBy == "") {
        this.$message.warning("序号不能为空");
        return;
      }
      if (!tool.judge("integer0", this.form.orderBy)) {
        this.$message.warning("序号需为正整数");
        return;
      }
      if (parseInt(this.form.orderBy) > 999) {
        this.$message.warning("序号不能超过999");
        return;
      }
      if (this.form.subSubjectList.length == 0) {
          this.$message.warning("请输入子科目名称");
         return;
        }
      let paras = {
        name: this.form.name,
        orgId: user.orgId,
        orderBy: this.form.orderBy,
        subSubjectList: this.form.subSubjectList
      };
      api.subjectAdd(paras).then(function(data) {
        if (data.resultCode == 2000) {
          vm.dialogFormVisible = false;
          vm.form = {
            name: "",
            orderBy: "",
            subSubjectList: [],
            orgId: user.orgId
          };
          vm.initData();
          vm.$message({
            message: "添加科目成功",
            type: "success"
          });
        } else {
          vm.$message.error(data.message);
        }
      });
    },
    /**
     * 更新/编辑数据
     */
    updateCofim() {
      if(vm.inputVisible) return;
      if (this.form_update.name == "") {
        this.$message.warning("科目名称不能为空");
        return;
      }
      if (!tool.judge("classname", this.form_update.name)) {
        this.$message.warning("请输入有效的科目名称");
        return;
      }
      console.log(this.form_update.orderBy);
      if (this.form_update.orderBy == "" && this.form_update.orderBy != 0) {
        this.$message.warning("序号不能为空");
        return;
      }
      if (!tool.judge("integer0", this.form_update.orderBy)) {
        this.$message.warning("序号需为正整数");
        return;
      }
      if (parseInt(this.form_update.orderBy) > 999) {
        this.$message.warning("序号不能超过999");
        return;
      }
      if (this.form_update.subSubjectList.length == 0) {
        this.$message.warning("请输入有效的子科目名称");
        return;
      }
      let paras = {
        name: this.form_update.name,
        isDelete: "0",
        orgId: this.form_update.orgId,
        orderBy: this.form_update.orderBy,
        subSubjectList: this.form_update.subSubjectList,
        subjectId: this.form_update.subjectId
      };
      api.subjectUpdate(paras).then(function(data) {
        if (data.resultCode == 2000) {
          vm.dialogFormVisible_update = false;
          vm.form_update = {
            name: "",
            orderBy: "",
            orgId: 0,
            subjectId: 0,
            subSubjectList: []
          };
          vm.initData();
          vm.$message({
            message: "编辑科目成功",
            type: "success"
          });
        } else {
          vm.$message.error(data.message);
        }
      });
    },
    /**
     * 编辑按钮
     */
    handleEdit(index, row) {
      console.log(index, row);
      this.form_update = {
        name: row.name,
        orgId: row.orgId,
        orderBy: row.orderBy,
        subjectId: row.subjectId,
        subSubjectList: row.subSubjectList
      };
      this.dialogFormVisible_update = true;
    },
    /**
     * 删除按钮
     */
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将删除该科目, 是否继续?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          let paras = {
            subjectId: row.subjectId + ""
          };
          api.subjectDelete(paras).then(function(data) {
            if (data.resultCode == 2000) {
              vm.initData();
              vm.$message({
                message: "删除成功",
                type: "success"
              });
            } else {
              vm.$message.error(data.message);
            }
          });
        })
        .catch(() => {});
    },
    /**
     * 搜索科目
     */
    searchSubject() {
      if (this.searchText == "") return;
      this.tabledisplayObj.currentPage = 1;
      let paras = {
        name: this.searchText,
        currPage: 1,
        pageSize: this.tabledisplayObj.size
      }; //设置请求课程类型列表参数
      this.getData(paras);
      this.isShowSearch = true;
    }
  },
  mounted() {
    vm = this;
    user = tool.getItem(lsKey.user, true); //得到当前用户信息
    // if(user.roleMode>0){
    //   this.form.orgId = user.orgId;
    // }else{
    //   this.form.orgId = "";
    // }
    // api.orgList().then(function(data) {
    //   if (data.result == "操作成功") {
    //     vm.orgList = data.list;
    //   }
    // });
    this.initData();
  },
  computed: {}
};
</script>
<style lang="scss">
#subject_manage {
  .disable {
	pointer-events: none;
}
  .el-input__inner {
    border-radius: 0.08rem;
    font-size: 0.16rem;
    color: #666666;
    height: 0.36rem;
    line-height: 0.36rem;
  }
  .el-input__icon {
    line-height: 0.36rem;
  }

  .input_search {
    .el-input__inner {
      background-color: rgb(247, 248, 250);
    }
  }
  .newclassroomNumber {
    .el-input__inner {
      border-radius: 0.04rem;
      height: 0.4rem;
      line-height: 0.4rem;
    }
  }
  .el-tag:first-child {
    margin-right: 10px;
  }
  .el-tag {
    font-size: 0.16rem;
  }
  .el-tag + .el-tag {
    margin-right: 10px;
  }
  .button-new-tag {
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    vertical-align: bottom;
  }
}
</style>
<style scoped src="../../style/module/table.css"></style>
<style scoped src="../../style/clue_manage/clue_manage.css"></style>
<style scoped>
.right_btn {
  background-image: url(../../assets/img/clue_manage/add_white.png);
  width: 1.54rem;
}
</style>